import Vue 			from 'vue'
import util 		from '../../util'
import axios 		from 'axios'
import {BigNumber}  from 'bignumber.js';
import { Toast } 	from 'vant';
Vue.use(Toast);


export default {
	name: 'makeOrder',
	data(){
		return {
			payType:0,			//支付方式  1:支付宝  2:银行卡  3:微信
			showDetail:false,
			iconName:'',		//购买的币种类型
			dialogStatus:0,		//按钮点击状态	1:取消   2:付款
			showBox:false,		//是否显示弹窗
			isSelect:false,		//确认取消弹窗，是否勾选
			dropName:'',		//收款账户
			dropCode:'',		//收款账号
			bankName:'',		//收款银行名称
			orderNum:'',		//已成交单量
			showTimer:'',		//倒计时剩余时间
			orderInfo:{
				allPrice:0,		//总价
				account:0,		//购买币数量
				id:0,			//订单编号
			},
			orderId:'',			//当前页面承担非下单功能，保存订单ID
			from:'',			//来源
			isSell:0,			//是否是出售的订单
			dropAccount:'',		//收款地址
			ETHAccount:'',
			EOSAccount:'',
			ajaxBtn:false,
			logo:'',
			countDownTime:0,		//若是购买订单，则倒计时
			makeOrderDown:null,
		}
	},
	computed:{
		isIphoneX(){
			return util.isIphoneX()
		},
		isIphone(){
			return util.client()
		},
		isMYKEY(){
			return util.isMYKEY()
		}
	},
	methods:{
		getOrderInfo(){
			//拉取订单信息
			let _url = this.isSell==1?'/mykey/otc-outmoney-detail':'/otc/inmoney-detail';
			util.fetch(util.ajaxUrl()+_url,{
				token:util.getToken(),
				id:this.orderId
			}).then(res => {
				Toast.clear();
				if(res.retCode === 0){
					if(!this.isSell) this.ajaxBtn  = true;
					this.orderInfo.allPrice = res.retData.orderrmb.toFixed(2);		//总价
					this.orderInfo.id = res.retData.id;					//订单编号
					this.dropName = res.retData.outname;				//收款账户
					this.dropCode = res.retData.outaddr;				//收款账号
					this.bankName = res.retData.bank_name;				//收款银行
					this.orderNum = res.retData.finish_order_count;		//已成交单量
					this.orderInfo.account  = res.retData.orderusdt;	//数量
					this.iconName = res.retData.currency_id;
					this.payType  = (res.retData.outtype==3 || res.retData.outtype==4)?3:res.retData.outtype;				//支付方式
					if(this.isSell) this.getSellPackage(this.iconName);
					//判断图标icon
					let otcConfig = util.getStorage('otcConfig');
					if(otcConfig){
						otcConfig = JSON.parse(otcConfig);
						if(otcConfig && otcConfig.currency && otcConfig.currency[this.iconName] && otcConfig.currency[this.iconName].logo){
							this.logo = otcConfig.currency[this.iconName].logo;
						}
					}
					//开始倒计时
					let leftTime = res.retData.left_time || res.retData.lefttime;
					this.timer(leftTime);
					//是否置灰倒计时
					if(this.isSell != 1 && leftTime > 895){
						this.countDownTime = 6;
						this.grayCountDown();
					}
					sessionStorage.removeItem('makeOrderDown');
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				Toast.clear();
				console.log(error)
			})
		},
		timer(leftSec){
			if(leftSec <= 0){
				setTimeout(()=>{
					this.$router.replace({
						path:'/orderDetail',
						query:{
							id:this.orderId,
							pageState:this.isSell?2:1
						}
					})
				},1000)
			}else{
				let mins    = Math.floor(leftSec/60);          //分钟
                let seconds = leftSec - mins*60;               //秒
                //确保时分秒都是2位数
                mins        = mins.toString().length==1?'0'+mins:mins;
                seconds     = seconds.toString().length==1?'0'+seconds:seconds;
                this.showTimer = mins+':'+seconds;
                setTimeout(() => {
                	this.timer(leftSec-1)
                },1000)
			}
		},
		upload(status){
			// status  0:取消订单   1:确认订单
			if(status==0 && this.isSell==1 && this.isSelect){
				//mykey中取消订单
				this.changeOrderStatus(99);
				return
			}
			if(status===0 && !this.isSelect) return
			this.dialogStatus = 0;
			this.showBox = false;
			Toast.loading({
 				message: '加载中...',
  				forbidClick: true,
  				duration:10000
			});
			let str = '/mykey/otc-';
			let _url = status===0?str+'cancel-inmoney':str+'confirm-inmoney';
			util.fetch(util.ajaxUrl()+_url,{
				token:util.getToken(),
				id:this.orderInfo.id
			}).then(res => {
				Toast.clear();
				if(res.retCode === 0){
					Toast.clear();
					Toast.success(res.retMsg)
					setTimeout(()=>{
						if(this.orderId && this.from == 'orderList'){
							//订单详情页过来的情况
							util.setStorage('orderId',this.orderId)
							this.goBack('special');
							return
						}
						if(status == 0){
							//取消订单
							this.goBack('special');
							return
						}
						this.$router.replace({
							path:'/orderDetail',
							query:{
								id:this.orderInfo.id,
								pageState:1,
								death:1
							}
						})
					},1500)
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		},
		changeOrderStatus(state){
			//修改订单状态
			Toast.loading({
				message: '加载中...',
				duration:0,
				forbidClick: true
			});
			util.fetch(util.ajaxUrl()+`/mykey/otc-outmoeny-state`,{
				token:util.getToken(),
				id:this.orderInfo.id,
				state:state
			}).then(res => {
				Toast.clear();
				if(res.retCode === 0){
					this.$router.replace({
						path:'/orderDetail',
						query:{
							id:this.orderInfo.id,
							pageState:2
						}
					})
					// console.log(res)
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				Toast.clear();
				console.log(error)
			})
		},
		transfer(){
			//在mykey中交易
			try{
            	let self = this;
            	if(this.iconName === 'EOS'){
		            let network = ScatterJS.Network.fromJson(util.eosNetwork);
		            let scatter,eos;
		            ScatterJS.connect('LernaVanillaTest', { network }).then(connected => {
		                if (!connected) return false;
		                scatter = ScatterJS.scatter;
		                eos = scatter.eos(network, Eos);
		                let login = async () => {
		                    await ScatterJS.login();
		                    eos = scatter.eos(network, Eos);
		                    let account = ScatterJS.account('eos');
		                    let _account = Number(self.orderInfo.account)
		                    eos.transaction({
				                actions: [
				                    {
				                        account: "eosio.token",
				                        name: "transfer",
				                        authorization: [
				                            {
				                                actor: account.name,
				                                permission: "active"
				                            }
				                        ],
				                        data: {
				                            from: account.name,
				                            to: self.dropAccount.split('|')[0],
				                            quantity: (_account.toFixed(4))+" EOS",
				                            memo: self.dropAccount.split('|')[1]
				                        }
				                    }
				                ]
				            }).then(trx => {
				            	Toast.clear();
				            	if(trx){
				            		self.changeOrderStatus(1);
				            	}
				            }).catch(err => {
				            	Toast.clear();
				            	window.location.reload();
				            });
		                };
		                login();
		            });
	            }else{
	            	//售卖非EOS
	            	this.loading = true;
	            	//mykey中判断可能获取不到ETH地址问题
					if(this.iconName != 'EOS' && (!this.ETHAccount || this.ETHAccount==='undefined')){
						if(typeof web3 !== 'undefined'){
							this.loading = false;
							Dialog.confirm({
			                    title: '提示',
			                    message: '获取ETH地址失败，请先开通账号。若已开通，请稍后刷新重试',
			                    className:'sellType-dialog',
			                    cancelButtonColor:'#1989fa',
			                    confirmButtonText:'确定',
			                    cancelButtonText:'取消',
			                    overlayClass:'sellType-mark'
			                }).then(() => {
			                	window.location.reload();
			                }).catch(() => {
			                    console.log('cancel')
			                })
						}else{
							Toast('请先升级app到最新版本')
						}
						return
					}
	            	if(this.iconName === 'ETH'){
	            		//交易ETH币
	            		if(typeof web3 !== 'undefined'){
		            		web3.eth.sendTransaction({
					            from: self.ETHAccount,
					            to: self.dropAccount,
					            // value: util.accMul(self.orderInfo.account,util.exchanges[self.iconName]),
					            value: BigNumber(self.orderInfo.account).multipliedBy(util.exchanges[self.iconName]).toString(),
					            // gasPrice: "20000000000",
					            // gas: "21000",
					            // data: ""
					        }, function (error, result) {
					            if(!error && result){
					            	self.changeOrderStatus(1);
					        	}else{
					        		Toast("交易失败");
					        	}
					        });
				        }else{
				        	Toast("web3准备失败，请刷新重试");
				        }
	            	}else{
	            		//交易ETH代币
	            		if(typeof web3 !== 'undefined'){
	            			var mtkAbi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}];
					        var mtkContract = web3.eth.contract(mtkAbi).at(util.addressAbi[self.iconName]);
					        // let _amount = util.accMul(self.orderInfo.account,util.exchanges[self.iconName]);
					        let _amount = BigNumber(self.orderInfo.account).multipliedBy(util.exchanges[self.iconName]).toString();
					        mtkContract.transfer(self.dropAccount, _amount , function (error, result) {
					        	if(!error && result){
					        		self.changeOrderStatus(1);
					        	}else{
					        		Toast("交易失败");
					        	}
					        })
	            		}else{
	            			Toast("web3准备失败，请刷新重试");
	            		}
	            	}
	            }
            }catch(e){
            	Toast.clear();
            	console.log(e)
            }
		},
		showDialog(num){
			if(this.isMYKEY && this.isSell != 1 && this.countDownTime > 0){
				//倒计时中
				return
			}
			//是否显示弹窗
			if(this.isMYKEY && this.isSell == 1 && num == 2){
				this.transfer();
			}else{
				this.showBox = !this.showBox;
				this.isSelect = this.isSell == 1?true:false;
				if(num) this.dialogStatus = num;
			}
		},
		selectCancel(){
			//取消弹窗页面，是否勾选
			this.isSelect = !this.isSelect;
		},
		isOrderDetail(){
			//是否显示订单详情
			if(this.isSell == 1) return
			this.showDetail = !this.showDetail
		},
		goBack(special){
			util.navigateBack(-1,this,special)
		},
		copyText(target){
			//复制总价
			this.$copyText(target).then(() => {
				Toast('复制成功')
			}).catch(() => {
				Toast('复制失败')
			})
		},
		stop(){},
		service(){
			if(this.isMYKEY) return
			util.callHandler('openUrl',{
				url:'bbjApp://servicerinfo',
				title:'联系客服',
				needLogin:true,
				popVC:false,		//跳转的时候是否干掉当前页面
				hiddenNav:true,		//是否全屏
			},res => {
				console.log(res)
			})
		},
		getSellPackage(iconName){
			//获取转币地址
			util.fetch(util.ajaxUrl()+`/mykey/get-addr`,{
				token:this.token || util.getToken()
			}).then(res => {
				if(res.retCode === 0){
					this.ajaxBtn = true;
					this.dropAccount = res.retData[0][iconName];
				}else{
					Toast(res.retMsg || '未知错误')
				}
			}).catch(error => {
				console.log(error)
			})
		},
		grayCountDown(){
			this.countDownTime--;
			if(this.countDownTime > 0){
				setTimeout(() => {
					this.grayCountDown();
				},1000)
			}
		}
	},
	created() {
		Toast.loading({
			message: '加载中...',
			duration:0,
			forbidClick: true
		});
		let makeOrderDown = sessionStorage.getItem('makeOrderDown');
		if(makeOrderDown) {
			this.countDownTime = 6;
		};
		util.waitSDKReady().then(token => {
			let _query = this.$route.query;
			if(_query.orderId){
				this.token = token;
				this.orderId = _query.orderId;
				this.from    = _query.from;
				this.ETHAccount = util.getStorage('ETHAccount');
				this.EOSAccount = util.getStorage('EOSAccount');
				if(this.from && this.from == 'orderList' && !_query.noSession) sessionStorage.setItem('pageState',2)
				if(_query.isSell){
					this.isSell = _query.isSell;
					this.showDetail = true;
				}
				this.getOrderInfo();
			}else{
				Toast('获取数据有误，请返回重试')
			}
		}).catch((e) => {
			Toast('获取token失败')
		})
		setTimeout(() => {
			util.registerHandler('refreshCommonRequestWhenGoBackView',res => {
				window.location.reload();
				util.callHandler('setStatusBarStyle',{
					style:'light'
				})
			})
			//退出登录的时候native调用H5方法清除token缓存
			util.registerHandler('loginOutDeleteToken',res => {
				localStorage.removeItem('token');
			})
			util.callHandler('setStatusBarStyle',{
				style:'dark'
			})
		},500)
    }
}